<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class mdl_transaksi_keuangan extends CI_Model {
    
	function __construct(){
        parent::__construct();
    }
	
	function get_data($plimit = true){
		# get parameter from easy grid
		$page = isset($_POST['page']) ? intval($_POST['page']) : 1;  
		$limit = isset($_POST['rows']) ? intval($_POST['rows']) : 10;
		$sort = isset($_POST['sort']) ? strval($_POST['sort']) : 'id';  
		$order = isset($_POST['order']) ? strval($_POST['order']) : 'asc';  
		$offset = ($page-1)*$limit;
		
		#get filter
		//$nama_desa = isset($_POST['nama_desa']) ? strval($_POST['nama_desa']) : '';
		
		# create query
		$this->db->flush_cache();
		$this->db->start_cache();
			$this->db->select('a.tgl_posting, a.tgl_transaksi, a.kode_akun, b.deskripsi as akun, a.debit, a.kredit, a.saldo, a.referensi, a.deskripsi');
			$this->db->from('transaksi_keuangan a');
			$this->db->join('akun b', 'b.kode_akun = a.kode_akun');
			
			$this->db->like('tgl_posting', date('Y-m-d'), 'after');
			
			$this->db->order_by('id', 'ASC');
		$this->db->stop_cache();
		
		# get count
		$tmp['row_count'] = $this->db->get()->num_rows();
		
		# get data
		if($plimit == true){
			$this->db->limit($limit, $offset);
		}
		$tmp['row_data'] = $this->db->get();
		
		return $tmp;
	}

	function togrid($data, $count=0){
		if($count>0){
			$i=0;
			foreach($data->result_array() as $row){
				foreach($row as $key => $value){
					$response->rows[$i][$key]=$value;
				}
				$i++;
			}
			$response->total = $count;
		}else{
		$response->rows = array();
		}
		return json_encode($response);
	}
	
	function InsertOnDb($data){
		$saldo = 0;

		// get saldo terakhir
		$res = $this->db->query("SELECT saldo FROM transaksi_keuangan ORDER BY id DESC LIMIT 1;");
		if($res->num_rows() > 0)
			$saldo = $res->row()->saldo;

		// hitung saldo
		if($data['tipe'] == '1'){ // pemasukan
			$saldo += $data['nominal'];
		}else{ // pengeluaran
			$saldo -= $data['nominal'];
		}

		// proses insert
		$this->db->flush_cache();
        $this->db->set('kode_akun', $data['kode_akun']);
        $this->db->set('tgl_transaksi', FormatDateToMysql($data['tgl_transaksi']));
        $this->db->set('tgl_posting', date('Y-m-d H:i:s'));
        //$this->db->set('referensi', $data['referensi']);
        $this->db->set('deskripsi', $data['deskripsi']);
        
        if($data['tipe'] == '1'){ // pemasukan
        	$this->db->set('debit', $data['nominal']);
        	$this->db->set('kredit', '0');
        }else{
        	$this->db->set('debit', '0');
        	$this->db->set('kredit', $data['nominal']);
        }

        $this->db->set('saldo', $saldo);

        return $this->db->insert('transaksi_keuangan');
	}

}

?>